
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据录入页面</title>
    <script src="static/js/tailwindcss.3.4.17.js"></script>
    <link rel="stylesheet" href="static/css/all.min.css">
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <!-- 头部信息 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-2xl font-bold text-gray-800">数据录入系统</h1>
                    <p class="text-gray-600">请根据右侧表格信息填写左侧表单</p>
                </div>
                <div class="text-right">
                    <div class="text-sm text-gray-500">当前题目</div>
                    <div id="currentQuestion" class="text-xl font-semibold text-blue-600">#1</div>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="flex flex-col lg:flex-row gap-6">
            <!-- 左侧表单区域 (4/5宽度) -->
            <div class="lg:w-3/5">
                <div class="bg-white rounded-xl shadow-md p-6">
                    <form id="dataForm" class="space-y-6">
                        <!-- 动态表单字段将在这里生成 -->
                        <div id="formFields" class="space-y-4"></div>
                        
                        <!-- 按钮区域 -->
                        <div class="flex justify-between pt-6 border-t border-gray-200">
                            <button type="button" id="nextBtn" 
                                class="bg-green-500 hover:bg-green-600 text-white font-semibold py-3 px-6 rounded-lg transition-all transform hover:scale-105 flex items-center">
                                <i class="fas fa-arrow-right mr-2"></i>下一题
                            </button>
                            
                            <button type="button" id="submitBtn" 
                                class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-3 px-6 rounded-lg transition-all transform hover:scale-105 flex items-center">
                                <i class="fas fa-paper-plane mr-2"></i>提交
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 右侧表格区域 (1/5宽度) -->
            <div class="lg:w-2/5">
                <div class="bg-white rounded-xl shadow-md p-6 h-full">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-table mr-2 text-blue-500"></i>数据表格
                    </h2>
                    
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white border border-gray-200">
                            <thead>
                                <tr class="bg-gray-50">
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">键</th>
                                    <th class="py-2 px-3 border-b text-left text-xs font-medium text-gray-500 uppercase tracking-wider">值</th>
                                </tr>
                            </thead>
                            <tbody id="tableBody" class="divide-y divide-gray-200">
                                <!-- 表格内容将在这里动态生成 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 从URL参数或sessionStorage获取数据
            const urlParams = new URLSearchParams(window.location.search);
            let currentIndex = parseInt(urlParams.get('index')) || parseInt(sessionStorage.getItem('currentIndex')) || 0;
            let questionData = JSON.parse(urlParams.get('data'));
            
            if (!questionData) {
                alert('数据加载失败，请返回重新访问');
                window.location.href = '/';
                return;
            }
            
            let data = sessionStorage.getItem('questionData_'+questionData.id);
            if (data){
                data = JSON.parse(data);
                sessionStorage.setItem('currentIndex', currentIndex);
                // 更新当前题目显示
                document.getElementById('currentQuestion').textContent = `#${currentIndex+1}`;
                // 渲染当前题目
                renderQuestion(currentIndex, data);
                // 绑定按钮事件
                document.getElementById('nextBtn').addEventListener('click', function() {
                    handleNextQuestion(currentIndex, questionData);
                });
                document.getElementById('submitBtn').addEventListener('click', function() {
                    handleSubmit(currentIndex, questionData);
                });
            }
            else
                fetch('/question/'+questionData.id)
                    .then(response => response.json())
                    .then(data => {
                        // 将数据存储在sessionStorage中以便页面B使用
                        sessionStorage.setItem('questionData_'+questionData.id, JSON.stringify(data));
                        sessionStorage.setItem('currentIndex', currentIndex);
                        // 更新当前题目显示
                        document.getElementById('currentQuestion').textContent = `#${currentIndex+1}`;
                        // 渲染当前题目
                        renderQuestion(currentIndex, data);
                        // 绑定按钮事件
                        document.getElementById('nextBtn').addEventListener('click', function() {
                            handleNextQuestion(currentIndex, questionData);
                        });
                        document.getElementById('submitBtn').addEventListener('click', function() {
                            handleSubmit(currentIndex, questionData);
                        });
                    })
                    .catch(error => {
                        console.error('获取数据失败:', error);
                        document.getElementById('errorText').textContent = '网络请求失败，请重试';
                        errorDiv.classList.remove('hidden');
                    });
 
        });

        function renderQuestion(index, data) {
            const currentQuestion = data[index]; // 转换为0-based索引
            if (!currentQuestion) {
                alert('题目数据不存在');
                return;
            }
            
            const formFields = document.getElementById('formFields');
            const tableBody = document.getElementById('tableBody');
            
            // 清空现有内容
            formFields.innerHTML = '';
            tableBody.innerHTML = '';
            console.log(currentQuestion);
            
            // 渲染表单字段和表格
            currentQuestion.forEach((value) => {
                let key = value.label;
                // 渲染表格行
                const tableRow = document.createElement('tr');
                tableRow.className = 'hover:bg-gray-50';
                tableRow.innerHTML = `
                    <td class="py-2 px-3 border-b text-sm text-gray-800 font-medium">${key}</td>
                    <td class="py-2 px-3 border-b text-sm text-gray-600">${value.value}</td>
                `;
                tableBody.appendChild(tableRow);
                
                // 渲染表单字段
                const formField = document.createElement('div');
                formField.className = 'space-y-2';
                
                const label = document.createElement('label');
                label.className = 'block text-sm font-medium text-gray-700';
                label.textContent = key;
                
                let inputElement;
                
                if (value.type==='select') {
                    // 下拉框类型
                    inputElement = document.createElement('select');
                    inputElement.className = 'w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all';
                    value.options.forEach(option => {
                        const optionElement = document.createElement('option');
                        optionElement.value = option;
                        optionElement.textContent = option;
                        inputElement.appendChild(optionElement);
                    });
                } else {
                    // 输入框类型
                    inputElement = document.createElement('input');
                    inputElement.type = 'text';
                    inputElement.className = 'w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all';
                    inputElement.placeholder = `请输入${key}`;
                }
                
                inputElement.name = key;
                inputElement.id = `field_${key}`;
                
                formField.appendChild(label);
                formField.appendChild(inputElement);
                formFields.appendChild(formField);
            });
        }

        function handleNextQuestion(currentIndex, qData) {
            const formData = collectFormData();
            
            // 调用保存接口
            fetch('/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    form_data: formData,
                    question_id: qData.id,
                    current_index: currentIndex
                })
            })
            .then(response => {
                if (response.status === 200) {
                    const newIndex = currentIndex + 1;
                    let data = sessionStorage.getItem('questionData_'+qData.id);
                    // 检查是否还有下一题
                    if (newIndex <= data.length) {
                        sessionStorage.setItem('currentIndex', newIndex.toString());
                        window.location.href = `page_b.html?index=${newIndex}&data=${encodeURIComponent(JSON.stringify(qData))}`;
                    } else {
                        alert('已经是最后一题了');
                    }
                } else {
                    alert('保存失败，请重试');
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('网络错误，保存失败');
            });
        }

        function handleSubmit(currentIndex, qData) {
            const formData = collectFormData();
            
            // 调用提交接口
            fetch('/commit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    form_data: formData,
                    question_id: qData.id,
                    current_index: currentIndex
                })
            })
            .then(response => {
                if (response.status === 200) {
                    alert('提交成功！');
                    // 可以跳转到结果页面或首页
                    window.location.href = '/result?question_id='+qData.id;
                } else {
                    alert('提交失败，请重试');
                }
            })
            .catch(error => {
                console.error('提交失败:', error);
                alert('网络错误，提交失败');
            });
        }

        function collectFormData() {
            const formData = {};
            const formElements = document.getElementById('dataForm').elements;
            
            for (let element of formElements) {
                if (element.name) {
                    formData[element.name] = element.value;
                }
            }
            
            return formData;
        }
    </script>
</body>
</html>
